(function () {
    let container = document.querySelector('#container1'),
        slides = Array.from(container.querySelectorAll('.wrapper .slide')),
        paginationList = Array.from(container.querySelectorAll('.pagination span')),
        [btnPrev, btnNext] = Array.from(container.querySelectorAll('.btn'))
    /*  
        count: 记录slide数量的
        interval: 记录多久切换一次，单位ms
        step :记录当前展示slide的索引
        timer: 记录自动切换定时器的返回值
        prev: 记录上一个展示slide的索引
    */
    let count = slides.length,
        interval = 1500,
        timer = null,
        step = 0,
        prev = step

    /* 默认选中 */
    slides[step].style.cssText = 'z-index:1;opacity:1'
    paginationList[step].className = 'active'


    /* 分页器对齐 */
    const paginationFocus = function paginationFocus() {
        let temp = step
        paginationList.forEach((item, index) => {
            item.className = index === temp ? 'active' : ''
        })
    }

    // 向右/向左切换
    const move = function move() {
        let slideNow = slides[step],
            slidePrev = slides[prev]
        // 先改层级
        slideNow.style.zIndex = 1
        slidePrev.style.zIndex = 0
        // 再改透明度
        slideNow.style.transitionDuration = '.3s'
        slideNow.style.opacity = 1
        slideNow.ontransitionend = function () {
            slidePrev.style.transitionDuration = '0s'
            slidePrev.style.opacity = 0
        }
        // 当前展示索引就是下一个要展示的上一张    
        prev = step
        // 分页器对齐
        paginationFocus()
    }
    /* 向右切换【向左移动】 */
    const moveRight = function moveRight() {
        step++
        if (step >= count) step = 0
        move()
    }



    /* 向左切换【向右移动】 */
    const moveLeft = function moveRight() {
        step--
        if (step < 0) step = count - 1
        move()
    }

    /* 一系列操控 */
    // 开启自动轮播
    if (timer === null) timer = setInterval(moveRight, interval)

    // 鼠标进入和离开容器，控制自动轮播的暂停和开启
    container.onmouseenter = function () {
        if (timer) {
            clearInterval(timer)
            timer = null
        }
    }
    container.onmouseleave = function () {
        if (timer === null) timer = setInterval(moveRight, interval)
    }

    // 在浏览器页卡隐藏和显示的时候，控制定时器暂定和开启
    document.onvisibilitychange = function () {
        if (document.hidden) {
            // 当前页卡隐藏了
            if (timer) {
                clearInterval(timer)
                timer = null
            }
            return
        }
        // 当前页卡显示了
        if (timer === null) timer = setInterval(moveRight, interval)
    }

    // 点击左右导航按钮
    btnPrev.onclick = utils.throttle(moveLeft)
    btnNext.onclick = utils.throttle(moveRight)

    // 点击分页器切换
    paginationList.forEach((item, index) => {
        item.onclick = function () {
            if (step === index) return
            step = index
            move()
        }
    })
})();